﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodeBuilder.DTO
{
    public class CreateDto
    {
        private string tableName;
        private string fileDir;
        private DataTable dataTable;
        public CreateDto(string tableName, string fileDir, DataTable dataTable)
        {
            this.tableName = tableName;
            this.fileDir = fileDir;
            this.dataTable = dataTable;
        }

        public void Run()
        {
            var formatTableName = Helper.GetPascalCase(tableName).Substring(1);
            var dtoName = formatTableName + "Dto";
            IList<string> contents = new List<string>();
            contents.Add($"using CommunityToolkit.Mvvm.ComponentModel;");
            contents.Add($"");
            contents.Add($"namespace Hualong.TestWorldPro.Dto");
            contents.Add("{");
            contents.Add($"    public partial class {formatTableName}Dto : DtoBase");
            contents.Add("    {");
            foreach (DataRow fieldItem in dataTable.Rows)
            {
                if (fieldItem[0].ToString() == "id" || fieldItem[0].ToString() == "sort"
                    || fieldItem[0].ToString() == "is_deleted" || fieldItem[0].ToString() == "create_user"
                    || fieldItem[0].ToString() == "create_time" || fieldItem[0].ToString() == "update_user"
                    || fieldItem[0].ToString() == "update_time")
                    continue;
                contents.Add($"        [ObservableProperty]");
                var notNull = "?";
                var extEmpty = "";
                if (fieldItem[2].ToString() == "NO" || fieldItem[1].ToString() == "float" || fieldItem[1].ToString() == "double" || fieldItem[1].ToString().Equals("tinyint(1)", StringComparison.OrdinalIgnoreCase))
                {
                    notNull = "";
                }
                if (DataTypeMap.Get(fieldItem[1].ToString()) == "string")
                {
                    notNull = "";
                    extEmpty = " = string.Empty";
                }
                contents.Add($"        private {DataTypeMap.Get(fieldItem[1].ToString())}{notNull} {Helper.GetCamelCase(fieldItem[0].ToString())}{extEmpty};");
            }
            contents.Add("    }");
            contents.Add("}");
            string filePath = fileDir;

            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
            filePath = Path.Combine(filePath, $"{dtoName}.cs");
            if (File.Exists(filePath))
            { File.Delete(filePath); }
            File.WriteAllLines(filePath, contents, Encoding.UTF8);


            Console.WriteLine($"创建:{filePath} 完成！");
        }
    }
}
